package com.ruoyi.web.core.config;

import cn.hutool.core.collection.ListUtil;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.listener.*;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiImageModel;
import dev.langchain4j.service.AiServices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Map;


@Configuration
public class LLMOpenApiConfig {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${langchain4j.open-ai.chat-model.api-key}")
    private String apiKey;
    @Value("${langchain4j.open-ai.chat-model.model-name}")
    private String modelName;
    @Value("${langchain4j.open-ai.chat-model.base-url}")
    private String baseUrl;

    @Bean
    public ChatLanguageModel openAiChatModel() {

        ChatModelListener listener = new ChatModelListener() {
            @Override
            public void onRequest(ChatModelRequestContext requestContext) {
                ChatModelRequest request = requestContext.request();
                Map<Object, Object> attributes = requestContext.attributes();
                // 记录请求
                logger.info("Chat model request: {}", request);
                if (attributes != null) {
                    logger.debug("Request attributes: {}", attributes);
                }
            }

            @Override
            public void onResponse(ChatModelResponseContext responseContext) {
                ChatModelResponse response = responseContext.response();
                ChatModelRequest request = responseContext.request();
                Map<Object, Object> attributes = responseContext.attributes();
                // 记录响应
                logger.info("Chat model response: {}", response);
                if (attributes != null) {
                    logger.debug("Response attributes: {}", attributes);
                }
            }

            @Override
            public void onError(ChatModelErrorContext errorContext) {
                // 从错误上下文中获取错误信息
                Throwable error = errorContext.error();
                // 获取导致错误的请求
                ChatModelRequest request = errorContext.request();
                // 获取部分响应（如果有）
                ChatModelResponse partialResponse = errorContext.partialResponse();
                // 获取错误的附加属性
                Map<Object, Object> attributes = errorContext.attributes();
                // 记录错误信息，包括请求和错误详情
                logger.error("Chat model error occurred for request: {}, error: {}", request, error, error);
                // 如果有部分响应，记录警告信息
                if (partialResponse != null) {
                    logger.warn("Partial response: {}", partialResponse);
                }
                // 如果有附加属性，记录调试信息
                if (attributes != null) {
                    logger.debug("Error attributes: {}", attributes);
                }
            }


        };

        return OpenAiChatModel.builder()
                .apiKey(apiKey)
                .modelName(modelName)
                .baseUrl(baseUrl)
                .listeners(ListUtil.of(listener))
                .timeout(Duration.ofSeconds(30))
                .temperature(0d)
                .build();

    }

    /**
     * 文生图
     * 通义万相-文生图2.1-Turbo
     * @return
     */
    @Bean
    public OpenAiImageModel OpenAiImageModel() {
        return OpenAiImageModel.builder()
                .apiKey(apiKey)
                .modelName(modelName)
                .baseUrl(baseUrl)
                .timeout(Duration.ofSeconds(30))
                .build();
    }


    @Bean
    public OpenApiChatAssistant openAiChatAssistant() {
        return AiServices.builder(OpenApiChatAssistant.class)
                .chatLanguageModel(openAiChatModel())
                .build();
    }
}
